package com.oocl.servlet.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.oocl.pojo.CartItem;
import com.oocl.pojo.Dish;
import com.oocl.pojo.JSONResponse;
import com.oocl.service.CartManager;
import com.oocl.service.DishManager;
import com.oocl.service.impl.CartManagerImpl;
import com.oocl.service.impl.DishManagerImpl;


@WebServlet("/addcartitem")
public class AddCartItemActionServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    private CartManager cartManager = new CartManagerImpl();
    private DishManager dishManager = new DishManagerImpl();
    private ObjectMapper mapper = new ObjectMapper();
    private String jsonStr;
	
    public AddCartItemActionServlet() {
        super();

    }
    
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setCharacterEncoding("UTF-8");                      //解决中文乱码
		response.setHeader("Access-Control-Allow-Origin", "*");
		response.setHeader("content-type","text/html;charset=UTF-8");//解决中文乱码
		Integer code = 1;
		String dId = request.getParameter("did");
//		CartItem cartItem = new CartItem(dId,"apple",0,1.0);//test
		Dish dish = dishManager.findDishById(dId);
		CartItem cartItem = new CartItem(dish.getdId(), dish.getdName(), 0, dish.getdPrice(),dish.getdImage());
		Map<String, CartItem> cart = (Map<String, CartItem>)request.getSession().getAttribute("cart");
		if(cart==null)cart = new ConcurrentHashMap<String, CartItem>();
		cartManager.addCartItem(cart, cartItem);
		request.getSession().setAttribute("cart", cart);
		JSONResponse<CartItem> jsonResponse = new JSONResponse<CartItem>();
		jsonResponse.setCode(code);
		jsonResponse.setMsg("操作成功:"+dish.getdName());
		jsonStr = mapper.writeValueAsString(jsonResponse);
		PrintWriter out = response.getWriter();
		out.println(jsonStr);
	}


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
